package sword.offer;

import sword.offer.common.GenerateList;
import sword.offer.common.ListNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Stack;

/**
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 *
 * @author 胡宇轩
 * @link https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
 * @Email: yuxuan.hu01@bianlifeng.com
 */
public class Six {
    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
        solution1.reversePrint(GenerateList.generate(new int[]{1, 3, 2}));
    }
}

class Solution {
    public int[] reversePrint(ListNode head) {
        List<Integer> array = new ArrayList<>();

        solve(head,array);
        int[] result = new int[array.size()];
        for (int i=0; i<array.size(); i++){
            result[i] = array.get(i);
        }
        return result;
    }

    public void solve(ListNode head, List<Integer> array){
        if(Objects.isNull(head)){
            return;
        }
        solve(head.next, array);
        array.add(head.val);
    }
}

/**
 * 使用栈的方式
 * */
class Solution1 {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        while(head != null){
            stack.push(head.val);
            head = head.next;
        }
        int size = stack.size();
        int[] result = new int[size];
        for (int i = 0; i < size; i++) {
            result[i] = stack.pop();
        }
        return result;
    }
}
